package com.wantup.demo04mk.example.count;

import com.wantup.demo04mk.annoations.NotThreadSafe;
import com.wantup.demo04mk.annoations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName CountExample1
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/7/9  23:46
 * @Version 1.0
 */
@Slf4j
@ThreadSafe
public class CountExample2 {

    //请求总数
    public static int clientTotal = 5000;

    //同时并发执行的线程总数
    public static int threadTotal = 200;


    public static AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();
        //定义信号量 参数是允许并发的线程数
        Semaphore semaphore = new Semaphore(threadTotal);
        CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });

        }


        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        log.info("count:{}", count.get());

    }

    public static void add() {
        count.incrementAndGet();
    }

}
